<template>
  <div class="app-container">
    <h2 style="text-align: center">发布软笔资源包</h2>

    <el-steps
      :active="1"
      process-status="wait"
      align-center
      style="margin-bottom: 40px"
    >
      <el-step title="添加软笔书目录" />
      <el-step title="添加软笔书单元" />
      <el-step title="添加章节" />
    </el-steps>
    <div>
      <el-button
        type="primary"
        @click="addContents(0)"
        >新增</el-button
      >
    </div>
    <el-table
      :data="contentsList"
      stripe
      v-loading="dataListLoading"
      style="width: 100%"
    >
      <el-table-column
        prop="id"
        header-align="center"
        align="center"
        label="目录id"
      ></el-table-column>
      <el-table-column
        prop="bid"
        header-align="center"
        align="center"
        label="软笔书id"
      ></el-table-column>
      <el-table-column
        prop="corder"
        header-align="center"
        align="center"
        label="顺序"
      ></el-table-column>
      <el-table-column header-align="center" align="center" label="目录图片">
        <template slot-scope="scope">
          <el-image :src="scope.row.contents"></el-image>
        </template>
      </el-table-column>
      <el-table-column header-align="center" align="center" label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="next(scope.row.id)"
            >添加单元</el-button
          >
          <el-button
            type="text"
            size="small"
            @click="addContents(1, scope.row.id)"
            >修改</el-button
          >
          <el-button type="text" size="small" @click="deleteById(scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>
    <el-dialog
      :visible.sync="dialogContentsVisible"
      :title="type == 0 ? '添加软笔书目录信息' : '修改软笔书目录信息'"
    >
      <el-form
        :rules="dataRule"
        ref="contentsForm"
        :model="contents"
        label-width="120px"
      >
        <el-form-item label="顺序" prop="corder">
          <el-input-number
            v-model="contents.corder"
            controls-position="right"
            :min="1"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="目录图片" prop="contents">
          <el-upload
            class="avatar-uploader"
            :action="'http://121.41.167.195:8000/api/oss/upload'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="contents.contents"
              :src="contents.contents"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogContentsVisible = false">取 消</el-button>
        <el-button
          :disabled="saveContentsBtnDisabled"
          type="primary"
          @click="saveOrUpdate"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <div>
      <!-- <el-button @click="previous">上一步</el-button> -->
      <!-- <el-button :disabled="saveBtnDisabled" type="primary" @click="next"
        >下一步</el-button
      > -->
    </div>
  </div>
</template>

<script>
import Vue from "vue";
export default {
  data() {
    return {
      saveBtnDisabled: false, // 保存按钮是否禁用
      editionId: null,
      contents: {
        // 课本对象
        corder: 1,
        contents: "",
        bid: null,
        id: null,
      },
      contentsList: [], // 课本集合
      dataListLoading: false, // 加载课本数据
      pageIndex: 1, // 当前页
      pageSize: 10, // 每页数据显示几条
      totalPage: 0, // 总记录数
      type: 0, // 0:添加1:修改
      dialogContentsVisible: false, // 添加课本信息对话框
      saveContentsBtnDisabled: false, // 课本信息保存按钮是否禁用
      dataRule: {
        // 数据规则
        corder: [{ required: true, message: "顺序不能为空", trigger: "blur" }],
        contents: [{ required: true, message: "目录不能为空" }],
      },
    };
  },

  activated() {
    // 看看是哪里来的
    this.dataListLoading = true;
    this.$http({
      url: this.$http.adornUrl(
        `/sf/cbcontents/getBookIdById/${this.$route.params.id}`
      ),
      method: "get",
    }).then(({ data }) => {
      if (data && data.code === 0) {
        console.log(data);
        this.contents.bid = data.bookId; // 获取bookId
        // 回显数据
        this.getContentsByBookId();
      }
    });
  },

  methods: {
    // 获取课本分页数据
    getContentsByBookId() {
      this.dataListLoading = true;
      this.$http({
        url: this.$http.adornUrl(`/sf/cbcontents/list`),
        method: "get",
        params: this.$http.adornParams({
          page: this.pageIndex,
          limit: this.pageSize,
          bookId: this.contents.bid,
        }),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          console.log(data);
          this.contentsList = data.contentsPage.records;
          this.totalPage = data.contentsPage.total;
        } else {
          this.contentsList = [];
          this.totalPage = 0;
        }
        this.dataListLoading = false;
      });
    },
    //上传成功后的回调函数
    handleAvatarSuccess(response) {
      this.contents.contents = response.url;
    },
    beforeAvatarUpload() {},
    // 对话框中的保存或修改
    saveOrUpdate() {
      if (this.type == 0) {
        // 添加课本
        this.contentsFormSubmit();
      } else {
        // 修改课本
        this.$refs["contentsForm"].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl("/sf/cbcontents/update"),
              method: "post",
              data: this.$http.adornData(this.contents, false),
            }).then((response) => {
              this.$message({
                message: "修改成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.getContentsByBookId();
                  this.dialogContentsVisible = false;
                },
              });
            });
          }
        });
      }
    },
    // 打开对话框，添加、修改
    addContents(status, id) {
      // 重置表单
      this.$nextTick(() => {
        this.$refs["contentsForm"].resetFields();
      });
      if (status == 0) {
        // 添加
        this.type = 0;
        // 清空
        this.contents.contents = "";
      } else {
        // 修改
        this.type = 1;

        this.$http({
          url: this.$http.adornUrl("/sf/cbcontents/info/" + id),
          method: "get",
        }).then((response) => {
          this.contents = response.data.cbContents;
        });
      }
      this.dialogContentsVisible = true;
    },
    // 通过课本id删除课本
    deleteById(id) {
      this.$confirm(`确定对[目录id=${id}]进行[删除]操作?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/sf/cbcontents/delete"),
            method: "post",
            data: this.$http.adornData([id], false),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "删除成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.getContentsByBookId();
                },
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        })
        .catch(() => {});
    },
    // 表单提交
    contentsFormSubmit() {
      // 表单验证
      this.$refs["contentsForm"].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/sf/cbcontents/save`),
            method: "post",
            data: this.$http.adornData(this.contents, false),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "添加成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.getContentsByBookId();
                  this.dialogContentsVisible = false;
                },
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    },
    updateEdtion() {},
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.getContentsByBookId();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.getContentsByBookId();
    },
    // 上一步
    previous() {
      console.log("previous");
      this.$router.push({
        path: "/ruanbi/ruanbiBookAdd/" + this.contents.bid,
      });
    },
    // 下一步
    next(id) {
      this.$router.push({
        path: "/ruanbi/ruanbiUnitAdd/" + id,
      });
      // 记录到哪一步了和id
        this.$cookie.set("path", "ruanbiUnitAdd");
        this.$cookie.set("id", id);
    },
  },
};
</script>
<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
